package com.aisb.manage;

import com.aisb.common.CommonService;
import com.aisb.core.BaseService;
import com.aisb.core.InitParam;
import com.aisb.core.shiro.ShiroDao;
import com.aisb.core.util.DateUtil;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class RoleService extends BaseService {
    private final static Logger logger = LoggerFactory.getLogger(RoleService.class);


    @Autowired
    RoleDao roleDao;

    @Autowired
    AuthDao authDao;

    @Autowired
    ShiroDao shiroDao;

    @Autowired
    CommonService commonService;

    public Object roleOne(String roleId) {
        Map role = (Map) roleDao.queryOne(roleId);
        roleInfoFuncDeal(role);
        return role;
    }

    public Object roleOne(Map param) {
        Map role = (Map) roleDao.queryOne(param);
        roleInfoFuncDeal(role);
        return role;
    }

    public List roleList(Map param) {
        List<Map> roleList = roleDao.queryList(param);

        return roleList;
    }

    public Page roleList(Map param, Integer pageNum, Integer pageSize) {
        if (null == pageNum) {
            pageNum = 1;
        }
        if (null == pageSize) {
            pageSize = 999999;
        }

        // 地域信息
        Map<String, Map> areaMap = commonService.areaSimpleMap();

        Page roles = roleDao.searchPage(param, pageNum, pageSize);
        List<Map> result = roles.getResult();
        for (Map m : result) {
            // 地域信息
            String areaId = (String) m.get("areaId");
            Map areaInfo = areaMap.get(areaId);
            if (null != areaInfo) {
                m.put("areaName", areaInfo.get("name"));
            }
        }

        return roles;
    }

    @Transactional
    public int roleAdd(Map param, List<String> funcIds) {
        getSessionBean();

        try {
            // 保存角色基本信息
            roleDao.insert(param);

            // 保存角色-功能
            param.put("adminId", sessionBean.getUserId());
            param.put("adminName", sessionBean.getUserName());
            param.put("adminTime", DateUtil.getInstance().getToday(InitParam.FORMAT_TIME));

            for (String funcIdstr : funcIds) {
                String funcIdArr[] = funcIdstr.split(",");
                String funcId = funcIdArr[0];
                String padd = funcIdArr[1];
                String pmodify = funcIdArr[2];
                String pdelete = funcIdArr[3];
                String pupload = funcIdArr[4];
                String pdownload = funcIdArr[5];
                param.put("funcId", funcId);
                param.put("padd", padd);
                param.put("pmodify", pmodify);
                param.put("pdelete", pdelete);
                param.put("pupload", pupload);
                param.put("pdownload", pdownload);
                authDao.authAddRoleFunc(param);
            }
        } catch (Exception e) {
            logger.error(e.toString());
            return 0;
        }
        return 1;
    }

    public int roleModify(Map param) {
        return roleDao.update(param);
    }

    @Transactional
    public int roleDelete(Map param) {
        try {
            roleDao.delete(param);
            roleDao.deleteRoleFunc(param);
            roleDao.deleteRoleOper(param);
            roleDao.deleteRoleUser(param);
        } catch (Exception e) {
            logger.error(e.toString());
            return 0;
        }
        return 1;
    }

    private void roleInfoFuncDeal(Map role) {
        String roleId = (String) role.get("roleId");

        LinkedHashSet<String> roleFuncs = new LinkedHashSet<>();
        LinkedHashSet<String> roleOpers = new LinkedHashSet<>();

        // 功能权限和操作权限
        List<Map> funcs = shiroDao.funcAll();
        List<Map> funcByRoleList = shiroDao.funcByRole(roleId);
        List<Map> operByRoleList = shiroDao.operByRole(roleId);

        Set viewSet = new HashSet();
        Set addSet = new HashSet();
        Set modifySet = new HashSet();
        Set deleteSet = new HashSet();
        Set uploadSet = new HashSet();
        Set downloadSet = new HashSet();

        // 角色直接拥有的功能权限和操作权限
        for (Map m : funcByRoleList) {
            String funcId = (String) m.get("funcId");
            String pAdd = (String) m.get("pAdd");
            String pModify = (String) m.get("pModify");
            String pDelete = (String) m.get("pDelete");
            String pUpload = (String) m.get("pUpload");
            String pDownload = (String) m.get("pDownload");

            viewSet.add(funcId);
            if ("true".equals(pAdd)) {
                addSet.add(funcId);
            }
            if ("true".equals(pModify)) {
                modifySet.add(funcId);
            }
            if ("true".equals(pDelete)) {
                deleteSet.add(funcId);
            }
            if ("true".equals(pUpload)) {
                uploadSet.add(funcId);
            }
            if ("true".equals(pDownload)) {
                downloadSet.add(funcId);
            }
        }

        boolean addFlag = false;
        boolean modifyFlag = false;
        boolean deleteFlag = false;
        boolean uploadFlag = false;
        boolean downloadFlag = false;

        // 角色直接拥有的操作权限
        for (Map m : operByRoleList) {
            String pAdd = (String) m.get("pAdd");
            String pModify = (String) m.get("pModify");
            String pDelete = (String) m.get("pDelete");
            String pUpload = (String) m.get("pUpload");
            String pDownload = (String) m.get("pDownload");
            if ("true".equals(pAdd)) {
                addFlag = true;
            }
            if ("true".equals(pModify)) {
                modifyFlag = true;
            }
            if ("true".equals(pDelete)) {
                deleteFlag = true;
            }
            if ("true".equals(pUpload)) {
                uploadFlag = true;
            }
            if ("true".equals(pDownload)) {
                downloadFlag = true;
            }
        }

        for (Map func : funcs) {
            String funcId = (String) func.get("funcId");
            String funcName = (String) func.get("funcName");
            String funcUrl = (String) func.get("funcUrl");
            if (StringUtils.isBlank(funcUrl)) {
                continue;
            }
            if (funcUrl.endsWith("/")) {
                funcUrl = funcUrl.substring(0, funcUrl.length());
            }

            if (!viewSet.contains(funcId)) {
                continue;
            }
            roleFuncs.add(funcName);
            if (funcUrl.endsWith("/index")) {// 获取功能授权关键KEY
                funcUrl = funcUrl.replace("/index", "");
            }
            if (addSet.contains(funcId) || addFlag) {
                roleOpers.add(funcName + "【新增】");
            }
            if (modifySet.contains(funcId) || modifyFlag) {
                roleOpers.add(funcName + "【修改】");
            }

            if (deleteSet.contains(funcId) || deleteFlag) {
                roleOpers.add(funcName + "【删除】");
            }

            if (uploadSet.contains(funcId) || uploadFlag) {
                roleOpers.add(funcName + "【导入】");
            }

            if (downloadSet.contains(funcId) || downloadFlag) {
                roleOpers.add(funcName + "【导出】");
            }
        }
        role.put("roleFuncs", StringUtils.join(roleFuncs.toArray(), " / "));
        role.put("roleOpers", StringUtils.join(roleOpers.toArray(), " / "));
    }
}
